import {
  deleteSynchrony,
  executeAllSynchrony,
  executeSynchrony,
  getNextTriggerTimeSynchrony,
  pageSynchrony,
  repairSynchrony,
  startAllSynchrony,
  stopAllSynchrony,
  updateStateSynchrony
} from '@/services/api/api-datahub-synchrony';
import { ReloadOutlined, ToolOutlined } from '@ant-design/icons';
import { ActionType, ModalForm, ProColumns, ProTable } from '@ant-design/pro-components';
import { useAccess } from '@umijs/max';
import { Button, message } from 'antd';
import React, { useRef, useState } from 'react';
import AddSynchrony from './components/AddSynchrony';
import EditSynchrony from './components/EditSynchrony';
import LogSynchrony from './components/LogSynchrony';

interface DatahubSynchronyDrawerProps {
  onRefurbish: () => void;
}

const DatahubSynchrony: React.FC<DatahubSynchronyDrawerProps> = ({ onRefurbish }) => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();
  const [previewTimeOpen, setPreviewTimeOpen] = useState(false);
  const handleCancel = () => setPreviewTimeOpen(false);
  const [nextextTriggerTimeList, setNextextTriggerTimeList] = useState([]);
  const loadNextTriggerTime = async (scheduleConf: string, scheduleType: string) => {
    const res = await getNextTriggerTimeSynchrony({
      scheduleConf: scheduleConf,
      scheduleType: scheduleType,
    });
    if (res.code === 0) {
      setNextextTriggerTimeList(res.data);
    }
  };

  const [search, setSearch] = useState<string>('');

  const columns: ProColumns<DatahubSynchronyData.SynchronyPage>[] = [
    {
      title: '任务描述',
      dataIndex: 'jobDesc',
      ellipsis: true,
      search: false,
      align: 'center',
    },
    {
      title: '区域',
      dataIndex: 'areaName',
      key: 'areaName',
      align: 'center',
      search: false,
    },
    {
      title: 'cron',
      dataIndex: 'scheduleConf',
      ellipsis: true,
      search: false,
      align: 'center',
    },
    {
      title: '负责人',
      dataIndex: 'author',
      key: 'author',
      align: 'center',
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'triggerStatus',
      key: 'triggerStatus',
      align: 'center',
      search: false,
      valueType: 'select',
      valueEnum: {
        1: { text: '启动', status: 'Success' },
        0: { text: '关闭', status: 'Error' },
      },
    },
    {
      title: '上次运行时间',
      dataIndex: 'triggerLastTime',
      key: 'triggerLastTime',
      align: 'center',
      search: false,
    },
    {
      title: '下次运行时间',
      dataIndex: 'triggerNextTime',
      key: 'triggerNextTime',
      align: 'center',
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: '400px',
      render: (text, record, _, action) => [
        // <a
        //   key="editable"
        //   // onClick={() => {
        //   //   // action?.startEditable?.(record.id);
        //   // }}
        //   onClick={async () => {
        //     const response = await synchronyPretreatmentRecord({ id: record.id });
        //     if (response.code === 0) {
        //       message.success('同步成功');
        //     }
        //   }}
        // >
        //   同步
        // </a>,
        <LogSynchrony onRefurbish={function (): void {}} detailData={record} />,
        <ModalForm
          key={'show_modal_form'}
          title="下次执行时间"
          trigger={<a key="delete_record_a"> 下次执行时间</a>}
          autoFocusFirstInput
          modalProps={{
            width: 300,
            destroyOnClose: true,
          }}
          onOpenChange={(open) => {
            if (open) {
              loadNextTriggerTime(record.scheduleConf, record.scheduleType);
            } else {
            }
          }}
          submitter={false}
        >
          {/* <div style={{display:'flex',textAlign:'center',flexDirection:'column'}}> */}
          {nextextTriggerTimeList.map((item) => (
            <div>{item}</div>
          ))}
          {/* </div> */}
        </ModalForm>,
        <a
          key={'a_update_state_synchrony'}
          onClick={async () => {
            const response = await updateStateSynchrony({
              id: record.id,
              triggerStatus: Number(record.triggerStatus) === 0 ? '1' : '0',
            });
            if (response.code === 0) {
              message.success('修改成功');
              actionRef.current?.reload();
            }
          }}
        >
          {Number(record.triggerStatus) === 0 ? '启动' : '关闭'}
        </a>,
        <a
          key={'a_update_state_synchrony'}
          onClick={async () => {
            const response = await executeSynchrony({
              id: record.id,
              executorParam: record.executorParam,
            });
            if (response.code === 0) {
              message.success('同步成功');
              actionRef.current?.reload();
            }
          }}
        >
          执行一次
        </a>,
        <EditSynchrony
          key={'edit_source'}
          onRefurbish={() => {
            actionRef.current?.reset();
          }}
          detailData={record}
        />,
        <ModalForm
          key={'delete_record_modal_form'}
          title="是否删除"
          trigger={<a key="delete_record_a"> 删除</a>}
          autoFocusFirstInput
          modalProps={{
            width: 400,
            destroyOnClose: true,
          }}
          onFinish={async (values) => {
            const response = await deleteSynchrony({
              id: record.id,
              executorParam: record.executorParam,
            });
            if (response.code === 0) {
              message.success('删除成功！');
              actionRef.current?.reload();
              action?.reload();
              return true;
            }
          }}
        >
          该记录将会被删除，是否确定
        </ModalForm>,
        // <TableDropdown
        //   key="actionGroup"
        //   onSelect={() => action?.reload()}
        //   menus={[
        //     {
        //       key: 'copy', name: Number(record.triggerStatus) === 0 ? '启动' : '关闭', onClick: async () => {
        //         const response = await updateStateSynchrony({ id: record.id, triggerStatus: (Number(record.triggerStatus) === 0 ? '1' : '0') });
        //         if (response.code === 0) {
        //           message.success('修改成功');
        //         }
        //       }
        //     },
        //     {
        //       key: 'delete', name: '同步', onClick: async () => {
        //         const response = await synchronyPretreatmentRecord({ id: record.id });
        //         if (response.code === 0) {
        //           message.success('同步成功');
        //         }
        //       }
        //     },
        //   ]}
        // />,
      ],
    },
  ];

  return (
    <>
      <ProTable<DatahubSynchronyData.SynchronyPage>
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}) => {
          const response = await pageSynchrony({ ...params, name: search });

          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        rowKey="id"
        dateFormatter="string"
        bordered
        search={false}
        toolbar={{
          search: {
            onSearch: (value: string) => {
              setSearch(value);
              actionRef.current?.reloadAndRest();
            },
          },
        }}
        ghost
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 20,
        }}
        toolBarRender={(action) => [
          <AddSynchrony
            onRefurbish={() => {
              action?.reload();
            }}
          />,
          <Button
            type="primary"
            onClick={async () => {
              const response = await executeAllSynchrony();

              if (response.code === 0) {
                action?.reload();
              }
            }}
          >
            <ReloadOutlined />
            全部执行一次
          </Button>,
          <Button
            type="primary"
            onClick={async () => {
              const response = await startAllSynchrony();
              if (response.code === 0) {
                message.success('全部开启');
                action?.reload();
              }
            }}
          >
            <ReloadOutlined />
            全部开启
          </Button>,
          <Button
            type="primary"
            danger
            onClick={async () => {
              const response = await stopAllSynchrony();

              if (response.code === 0) {
                message.success('全部关闭');
                action?.reload();
              }
            }}
          >
            <ReloadOutlined />
            全部关闭
          </Button>,
          <Button
            type="primary"
            onClick={async () => {
              const response = await repairSynchrony();
              if (response.code === 0) {
                action?.reload();
              }
            }}
          >
            <ToolOutlined />
            修复调度器配置
          </Button>,
          <LogSynchrony onRefurbish={function (): void {}} detailData={{ id: '' }} />,
        ]}
      />
    </>
  );
};
export default DatahubSynchrony;
